package com.example.demo.test;

import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 执行sql文件插入课表数据
 * @author lizijian
 */
@Slf4j
@Component
public class DataBaseConnectionUtils {
    @Resource(name = "primaryDataSource")
    private DataSource dataSource;
    public synchronized  void runInsertSqlFile() throws IOException, SQLException {
        Connection connection=null;
        try{
            connection = DataSourceUtils.getConnection(dataSource);
            log.info("connection:"+connection);
            log.info("isClose："+connection.isClosed());
            ScriptRunner scriptRunner=new ScriptRunner(connection);
            scriptRunner.runScript(Resources.getResourceAsReader("insert.sql"));
        }catch (Exception e){
            log.error(e.getMessage());
            throw e;
        }finally {
            if(connection!=null){
                connection.close();
            }
        }
    }
}
